﻿using AyCodeLibs.StandardExtensions;
using AyCodeLibs.StandardExtensions.Extensions;
using AyCodeLibs.StandardExtensions.Models;
using AyFrame.Common.Enums;
using AyFrame.Dto;
using AyFrame.Dto.Auth;
using Prism.Commands;
using Prism.Mvvm;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AyFrame.Gateway.ConfigApp
{
    public class MainWindowViewModel : BindableBase
    {
        private EnumObject _selectedGateway;

        public EnumObject SelectedGateway
        {
            get => _selectedGateway;
            set => SetProperty(ref _selectedGateway, value);
        }

        private List<EnumObject> _gateways;
        public List<EnumObject> Gateways
        {
            get => _gateways;
            set => SetProperty(ref _gateways, value);
        }

        private List<OcelotGatewayView> _configs;
        public List<OcelotGatewayView> Configs
        {
            get => _configs;
            set => SetProperty(ref _configs, value);
        }

        private DelegateCommand _searchCommand;
        public DelegateCommand SearchCommand => _searchCommand ?? (_searchCommand = new DelegateCommand(Search));

        private DelegateCommand _addCommand;

        public DelegateCommand AddCommand => _addCommand ?? (_addCommand = new DelegateCommand(Add));

        private RestClient _httpClient = new RestClient("http://localhost:8486");
        private string _token;
        public MainWindowViewModel()
        {
            Gateways = typeof(GatewaySys).ToList();

            var req = new
            {
                loginName = "admin",
                password = "123456",
                cid = "root"
            };
            var request = new RestRequest("/Token", Method.POST);
            request.AddObject(req);
            var rst = _httpClient.Execute<TokenDto>(request);

            if (!rst.IsSuccessful || rst.Content.IsNullOrEmpty() || !rst.Data.IsSuccess) throw new Exception("登录失败");

            _token = rst.Data.Token;
        }

        private void Search()
        {
            var req = new OcelotSearchRequest
            {
                PageIndex = 1,
                PageSize = 5000
            };
            var request = new RestRequest("/api/gateway/search", Method.POST);
            request.AddHeader("Authorization", $"bearer {_token}");
            request.AddJsonBody(req);

            var rst = _httpClient.Execute<InnerResponse<PagedResult<OcelotGatewayView>>>(request);

            if (!rst.IsSuccessful || !rst.Data.IsSuccess)
            {
                Configs = null;
                return;
            }

            Configs = rst.Data.Data.Items;
        }

        private void Add()
        {

        }
    }
}
